//
//  BoardViewController.m
//  MazeG
//
//  Created by cdh on 11/2/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "BoardViewController.h"

//game states
#define kGameStateRunning 1
#define kGameStatePaused 2
#define kGameStateStopped 3
#define kAccelerometerFrequency 50
#define kFilterFactor 0.1

//speed for ball
#define kBallSpeedX 6
#define kBallSpeedY 6

// distance for goal
#define kMaxGoalDistance 12

// friction
#define kFrictionFactor 0.995
#define kReboundFactor 0.05

// swipe
#define kMinHorizontalSwipe 12
#define kMaxHorizontalSwipe 4
#define kMinVerticalSwipe 12
#define kMaxVerticalSwipe 4

@implementation BoardViewController

@synthesize gameState;
@synthesize theBall, goalHole;
@synthesize startPosition, ballVelocity, startTouchPosition;
@synthesize player_score, tapToBegin;

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	self.wantsFullScreenLayout = YES;

	[self setupBoardView];
	self.gameState = kGameStatePaused;
	[self configureAccelerometer];
	score = 0;
	ballVelocity = CGPointMake(0, 0);
	bounceVelocity = CGPointMake(0, 0);
	[NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(gameLoop) userInfo:nil repeats:YES];
	
}

-(void) configureAccelerometer {
	UIAccelerometer * theAccelerometer = [UIAccelerometer sharedAccelerometer];
	theAccelerometer.updateInterval = 1 / kAccelerometerFrequency;
	theAccelerometer.delegate = self;
}

-(void) accelerometer:(UIAccelerometer *) accelerometer didAccelerate:(UIAcceleration *) acceleration {
	CGFloat x, y;
	x = self.theBall.center.x;
	y = self.theBall.center.y;
	x = (acceleration.x * kFilterFactor) + (x * (1.0 - kFilterFactor));
	y = (acceleration.y * kFilterFactor) + (y * (1.0 - kFilterFactor));
	//z = (acceleration.x * kFilterFactor) + (x * (1.0 - kFilterFactor);
	
	[self updateBallPosition:x :y];
}

- (IBAction) endGame{
	// swich window's view from Board to Home
	[[self.view superview] sendSubviewToBack: self.view];
}

- (void) gameLoop {
	CGFloat delta_x, delta_y;
	if(gameState==kGameStateRunning)
	{
		
		theBall.center = CGPointMake(theBall.center.x + ballVelocity.x, theBall.center.y + ballVelocity.y);
		
		//if it is out of bounds of the view.. then switch direction of the velocity
		
		if(theBall.center.x > self.view.bounds.size.width || theBall.center.x <0)
			ballVelocity.x = - ballVelocity.x;
			
		
		if(theBall.center.y> self.view.bounds.size.height || theBall.center.y < 0)
			ballVelocity.y = -ballVelocity.y;

		ballVelocity.x = ballVelocity.x * kFrictionFactor;
		ballVelocity.y = ballVelocity.y * kFrictionFactor;
		
		delta_x = fabsf(theBall.center.x - goalHole.center.x);
		delta_y = fabsf(theBall.center.y - goalHole.center.y);
		
		if(delta_x <= kMaxGoalDistance && delta_y <= kMaxGoalDistance){
			gameState = kGameStatePaused;
			// animation
			score += 10;
			player_score.text = [NSString stringWithFormat:@"score: %i", score];
			goalHole.center = CGPointMake(10 + arc4random() % 290, 10 + arc4random()%430);
		}
		
	}
	else 
	{
		
		if(tapToBegin.hidden)
		{
			tapToBegin.hidden = NO;
		}
	}
	
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
	if(gameState == kGameStatePaused)
	{
		tapToBegin.hidden = YES;
		gameState = kGameStateRunning;
	}
	else if(gameState == kGameStateRunning)
	{
		startTouchPosition = [[touches anyObject] locationInView: self.view];
		//[self touchesMoved:touches withEvent:event];
	}	
}

-(void) touchesMoved: (NSSet *) touches withEvent: (UIEvent *) event {
	CGFloat dx, dy;
	CGPoint currentTouchPosition = [[touches anyObject] locationInView: self.view];
	
	// horizontal swipe -> x acceleration
	dx = currentTouchPosition.x - startTouchPosition.x;
	// vertical swipe -> y acceleration
	dy = currentTouchPosition.y - startTouchPosition.y;
	
	// accept either a horizontal swipe or vertical swipe but not both 
	if(fabsf(dy) <= kMaxVerticalSwipe){
		// horizontal swipe
		ballVelocity.x = (fabsf(dx) <= kBallSpeedX) ? dx : kBallSpeedX;
	} else if(fabsf(dx) <= kMaxHorizontalSwipe){
		// vertical swipe
		ballVelocity.y = (fabsf(dy) <= kBallSpeedY) ? dy : kBallSpeedY;
	}
}

-(void) touchesEnded: (NSSet *) touches withEvent: (UIEvent *) event {
	startTouchPosition = CGPointMake(0.0, 0.0);
}

-(void) touchesCancelled: (NSSet *) touches withEvent: (UIEvent *) event {
	startTouchPosition = CGPointMake(0.0, 0.0);
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
	
	[theBall release];
	[backgroundImage release];
	[goalHole release];
	[player_score release];
	[tapToBegin release];
}

- (void) setupBoardView {
	
	self.view.frame = [UIScreen mainScreen].applicationFrame;

	startPosition = CGPointMake(10, 10);
	
	// set up score label
	player_score = [[UILabel alloc] initWithFrame: CGRectMake(0.0, 0.0, 100.0, 20.0)];
	player_score.text = [NSString stringWithFormat:@"score: 0"];
	
	//set up tab to begin
	tapToBegin = [[UILabel alloc] initWithFrame: CGRectMake(self.view.center.x-75, self.view.center.y - 25, 150.0, 50.0)];
	tapToBegin.hidden = YES;
	tapToBegin.textAlignment = UITextAlignmentCenter;
	tapToBegin.text = [NSString stringWithFormat:@"TAP TO BEGIN"];
	
	// set up background image
	backgroundImage = [[UIImageView alloc] initWithImage: [UIImage imageNamed:@"bg.png"]];
	
	//backgroundImage.center = self.view.center;
	backgroundImage.center = CGPointMake(160, 220);
	backgroundImage.opaque = YES;
	
	// set up the holes
	goalHole = [[UIImageView alloc] initWithImage: [UIImage imageNamed:@"hole.png"]];
	goalHole.center = CGPointMake(self.view.center.x + 75, self.view.center.y + 125);
	
	// set up the sticks/wall
	
	// set up the ball
	theBall = [[UIImageView alloc] initWithImage: [UIImage imageNamed:@"ball.png"]];
	theBall.center = CGPointMake(self.view.center.x, self.view.center.y);
	theBall.opaque = YES;
	
	// add the views in order: background, holes, walls, ball
	[self.view addSubview: backgroundImage];
	// add holes
	[self.view addSubview: goalHole];
	// add walls
	// add ball
	[self.view addSubview: theBall];
	[self.view addSubview: player_score];
	[self.view addSubview: tapToBegin];
	
}
- (void) updateBallPosition: (CGFloat) x : (CGFloat) y {
	if( x >=0 && x < self.view.bounds.size.width && y >= 0 && y < self.view.bounds.size.height){
		theBall.center = CGPointMake(theBall.center.x + x, y);
	}
}

@end
